package com.wnxy.portal.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.portal.common.constant.RedisConstant;
import com.wnxy.portal.common.result.Result;
import com.wnxy.portal.entity.Address;
import com.wnxy.portal.entity.China;
import com.wnxy.portal.model.vo.AddressVo;
import com.wnxy.portal.service.IAddressService;
import com.wnxy.portal.service.IChinaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Jet
 * @since 2023-12-11
 */
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private IAddressService addressService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/findAll")
    public Result findAll(@RequestHeader("Authorization")String token){
        // SELECT * FROM t_address WHERE userId=1
        // 获取用户id
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        // 查询
        List<Address> addressList =
                addressService.list(Wrappers.lambdaQuery(Address.class).eq(Address::getUserId, userId));
        // 转换
        List<AddressVo> voList = addressList.stream().map(address -> {
            AddressVo addressVo = new AddressVo();
            addressVo.setId(address.getId());
            addressVo.setAddress(address.getProvince() + address.getCity() + address.getArea() + address.getDetailAddress());
            addressVo.setIsDefault(address.getIsDefault());
            return addressVo;
        }).collect(Collectors.toList());
        return Result.ok(voList);
    }

    // 查询所有的省份
    @GetMapping("/getAllProvince")
    public Result getAllProvince() {
        List<China> list = addressService.getAllProvince();
        return Result.ok(list);
    }

    // 根据省份id，查询城市
    @GetMapping("/getAllCities")
    public Result getAllCities(Integer provinceId) {
        List<China> list = addressService.getAllCities(provinceId);
        return Result.ok(list);
    }

    // 根据城市id，查询区域
    @GetMapping("/getAllAreas")
    public Result getAllAreas(Integer cityId) {
        List<China> list = addressService.getAllAreas(cityId);
        return Result.ok(list);
    }

    // 保存地址
    @PostMapping("/save")
    public Result save(@RequestBody Address address,@RequestHeader("Authorization")String token) {
        // 获取用户id
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        // 根据省份id，获取省份名称？   数据类型选择：string？  set？  hash
        String province = (String) redisTemplate.opsForHash().get(RedisConstant.CHINA_CACHE,address.getProvince());
        // 根据城市id，获取城市名称？
        String city = (String) redisTemplate.opsForHash().get(RedisConstant.CHINA_CACHE,address.getCity());
        // 根据区域id，获取区域名称？
        String area = (String) redisTemplate.opsForHash().get(RedisConstant.CHINA_CACHE,address.getArea());

        address.setProvince(province);
        address.setCity(city);
        address.setArea(area);
        address.setUserId(Long.parseLong(userId));
        address.setStatus("1");
        if ("1".equals(address.getIsDefault())) {
            // 修改其他地址为不是默认地址，isDefault = 0
            addressService.update(Wrappers.lambdaUpdate(Address.class)
                    .set(Address::getIsDefault,"0").eq(Address::getUserId,userId));
        }
        // 添加
        addressService.save(address);
        return Result.ok();
    }
}
